package com.halden.TRPG.aop;

import com.alibaba.fastjson.JSON;
import com.halden.TRPG.common.CodeEnum;
import com.halden.TRPG.utils.JwtUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@Component
@Aspect
public class LogInCheckAop {

    @Pointcut("@annotation(com.halden.TRPG.aop.LogInCheck)")
    public void logInAction(){}

    @Around("logInAction()")
    public Object toLogin(ProceedingJoinPoint joinPoint) {
        Object returnVal = null;
        //获取request和response
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        String method = request.getMethod();
        try {
            //预请求放行
            if (StringUtils.hasText(method) && method.equals("OPTIONS")) {
                returnVal = joinPoint.proceed();
            }
            //检查token
            String token = request.getHeader("Authorization");
            //失败不放行
            if (!StringUtils.hasText(token) || !JwtUtil.check(token)) {
                response.setStatus(301);
                response.setContentType("application/json;charset=UTF-8");
                try {
                    response.getWriter().write(JSON.toJSONString(CodeEnum.NOT_LOGIN_EXCEPTION));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else { //成功放行
                returnVal = joinPoint.proceed();
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return returnVal;
    }
}
